package filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        处理办法：拦截请求，提取cookie中sessionid，再到服务器中寻找这个id，
//        如果存在已经登录，不存在，则没有登录，返回浏览器，请求不后传
        servletRequest.setCharacterEncoding("utf-8");
        System.out.println("请求被loginFilter拦截");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=utf-8");
        if (session.getAttribute("name") == null) {
            response.getWriter().write("您还没有登录，不能进商城！三秒后转向登录页面");
            response.setHeader("Refresh", "3;URL=/login.html");
        } else {//已经登录，把sessionid通过cookies写入到响应消息中,放行
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            response.addCookie(cookie);
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
